package App.Job;

import App.Model.BaseEnum;
import App.Model.ConnectinManager;
import App.Model.ConnectionInfo;
import App.Model.Task.CrmTask;
import App.Model.Task.CrmTaskMember;
import App.Model.Task.CrmTaskReminder;
import App.Repository.TaskAuthRepository;
import App.Repository.XinGePushRepository;
import App.Service.XingeService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.java2d.pipe.SpanShapeRenderer;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by xw on 2019/4/23.
 */

public class TaskReminderJob implements Job, Serializable {


    private XingeService _xingeService = new XingeService();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            System.out.println("i am task reminder job2 ...");

            Date _nowDate = new Date();
            Calendar _nowCal = Calendar.getInstance();
            _nowCal.setTime(_nowDate);

            int _nowHour = _nowCal.get(Calendar.HOUR_OF_DAY);
            int _nowMinute = _nowCal.get(Calendar.MINUTE);
            int _nowDay = _nowCal.get(Calendar.DAY_OF_MONTH);
            int _nowWeek = _nowCal.get(Calendar.DAY_OF_WEEK);
            int _nowMonth = _nowCal.get(Calendar.MONTH);
            int _nowYear = _nowCal.get(Calendar.YEAR);

            SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            //  SimpleDateFormat _nowFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date _formatNow = _dataFormat.parse(_dataFormat.format(_nowDate));


            XinGePushRepository _pushRepository = new XinGePushRepository();
            List<CrmTaskReminder> _reminders = _pushRepository.getTaskReminders();

            List<String> _userids = new ArrayList<>();
            String _title = "";
            String _finalString = "";
            for (CrmTaskReminder r : _reminders) {
                int _repeattype = r.getRepeattype();
                String _taskid = r.getTaskid();

                List<CrmTask> _tasks = _pushRepository.getTaskInfo(_taskid);
                List<CrmTaskMember> _members = _pushRepository.getTaskMember(_taskid);

                if (_tasks != null && _tasks.size() > 0) {
                    CrmTask _taskInfo = _tasks.get(0);
                    String taskBegintime = _dataFormat.format(_taskInfo.getBegintime());
                    String _taskAddress = _taskInfo.getAddressname();
                    String _taskContent = _taskInfo.getContent();

                    List<Integer> _memberIds = _members.stream().map(CrmTaskMember::getUserid).collect(Collectors.toList());
                    _userids.clear();
                    for (Integer id : _memberIds) {
                        _userids.add(id.toString());
                    }
                    if (_userids == null || _userids.size() == 0) {
                        continue;
                    }

                    _title = _taskContent;
                    _finalString = "时间:" + taskBegintime;

                    //计算开始时间，和当前时间比较，
                    Date _taskBeginTime = _tasks.get(0).getBegintime();
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(_taskBeginTime);

                    int _minutes = r.getMinutes();
                    int _aheadtype = r.getAheadtype();
                    getNewBeginTime(cal, _minutes, _aheadtype);
                    Date _formatRunDate = _dataFormat.parse(_dataFormat.format(cal.getTime()));

                    //任务运行时间>=当前时间
                    if (!_formatRunDate.after(_formatNow)) {

                        int _hour = cal.get(Calendar.HOUR_OF_DAY);
                        int _minute = cal.get(Calendar.MINUTE);
                        int _day = cal.get(Calendar.DAY_OF_MONTH);
                        int _week = cal.get(Calendar.DAY_OF_WEEK);
                        int _month = cal.get(Calendar.MONTH);
                        int _year = cal.get(Calendar.YEAR);

                        if (_repeattype == BaseEnum.TaskRepeatType.Once.getTaskRepeatType()) {
                            if (_year == _nowYear && _month == _nowMonth && _day == _nowDay && _hour == _nowHour && _minute == _nowMinute) {
                                _xingeService.pushMessage(_taskid, r.getRecid(), _userids, _title, _finalString);
                            }
                        } else if (_repeattype == BaseEnum.TaskRepeatType.Day.getTaskRepeatType()) {
                            if (r.getAheadtype() > BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
                                continue;
                            }
                            if (_hour == _nowHour && _minute == _nowMinute) {
                                _xingeService.pushMessage(_taskid, r.getRecid(), _userids, _title, _finalString);
                            }
                        } else if (_repeattype == BaseEnum.TaskRepeatType.Week.getTaskRepeatType()) {
                            if (r.getAheadtype() > BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
                                continue;
                            }

                            if (_week == _nowWeek && _hour == _nowHour && _minute == _nowMinute) {
                                _xingeService.pushMessage(_taskid, r.getRecid(), _userids, _title, _finalString);
                            }
                        } else if (_repeattype == BaseEnum.TaskRepeatType.Month.getTaskRepeatType()) {

                            if (r.getAheadtype() > BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
                                continue;
                            }
                            if (_day == _nowDay && _hour == _nowHour && _minute == _nowMinute) {
                                _xingeService.pushMessage(_taskid, r.getRecid(), _userids, _title, _finalString);
                            }
                        } else if (_repeattype == BaseEnum.TaskRepeatType.Year.getTaskRepeatType()) {

                            if (r.getAheadtype() > BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
                                continue;
                            }
                            if (_month == _nowMonth && _day == _nowDay && _hour == _nowHour && _minute == _nowMinute) {
                                _xingeService.pushMessage(_taskid, r.getRecid(), _userids, _title, _finalString);
                            }
                        }
                    }
                    //end
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    private Date getNewBeginTime(Calendar cal, int _aheadValue, int _aheadtype) {
        if (_aheadtype == BaseEnum.TaskAheadType.Minute.getTaskAheadType()) {
            cal.add(Calendar.MINUTE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
            cal.add(Calendar.HOUR, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Day.getTaskAheadType()) {
            cal.add(Calendar.DATE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Month.getTaskAheadType()) {
            cal.add(Calendar.MONTH, -_aheadValue);
        }
        return cal.getTime();
    }
}